//
// @file：Codable+JW.swift
// @project：JWHelperKit
// @author：linjw(10126121@qq.com)
// @time: 2022/12/20
//  Copyright © 2018年 Linjw. All rights reserved.
//

import UIKit

public extension JWNamespaceWrapper where T: Encodable {
    
    /// 转成JSON模型类(dictionary/array)
    func toJsonObject(_ jsonReadOptions: JSONSerialization.ReadingOptions = .mutableContainers) -> Any? {
        return toData()?.jw.toJsonObject(jsonReadOptions)
    }
    
    /// 转成Data
    func toData() -> Data? {
        return try? JSONEncoder().encode(jwWrappedValue)
    }
    
}

public extension JWNamespaceWrapper where T: Decodable {
    
    /// 通过Data生成
    static func fromData(_ data: Data, using decoder: JSONDecoder = JSONDecoder()) -> T? {
        return try? decoder.decode(T.self, from: data)
    }
 
    /// 通过String生成
    static func fromString(_ string: String, using decoder: JSONDecoder = JSONDecoder()) -> T? {
        guard let data = string.data(using: .utf8) else { return nil }
        return try? decoder.decode(T.self, from: data)
    }
    
}
